package cn.lcsjsxy.yxc.ioandnetwork;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class URLTest1 {
    public static void main(String[] args) {
        HttpURLConnection urlConnection= null;
        InputStream is= null;
        FileOutputStream fos= null;
        try {
            URL url=new URL("http://localhost:8080/examples/wow.jpg");
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.connect();
            is = urlConnection.getInputStream();
            fos = new FileOutputStream("wow.jpg");

            byte[] buffer = new byte[1024];
            int len;
            while ((len=is.read(buffer))!=-1){
                fos.write(buffer,0,len);
            }

            System.out.println("下载完成");
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (is!=null)
                try {
                    is.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            if (fos!=null)
                try {
                    fos.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            if (urlConnection!=null)
                urlConnection.disconnect();
        }
    }
}
